import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/util/auth'
import {
  setTitle
} from '@/util/util'
import {
  validatenull
} from '@/util/validate'

// NProgress Configuration
NProgress.configure({
  showSpinner: false
})

function hasPermission(roles, permissionRoles) {
  if (!permissionRoles) return true
  return roles.some(role => permissionRoles.indexOf(role) >= 0)
}
const whiteList = ['/login', '/404', '/401', '/lock']
const lockPage = '/lock'

router.beforeEach((to, from, next) => {
  // start progress bar
  NProgress.start();
  /*const value = to.query.src ? to.query.src : to.path
  const label = to.query.name ? to.query.name : to.name*/
  /*if (whiteList.indexOf(value) === -1) {
    store.commit('ADD_TAG', {
      label: label,
      value: value,
      query: to.query
    })
  }*/

  let cookieToken = getToken();
  if (store.getters.access_token != cookieToken){ // 如果vuex与cookie不一致
    if(!validatenull(cookieToken)){ // 以cookie为主
      if (!store.getters.access_token){
        store.commit('SET_ACCESS_TOKEN', cookieToken);
      }
    } else { // 否则清空
        store.dispatch('FedLogOut');
    }
  }

  if (store.getters.access_token) { // determine if there has token
    //console.log(validatenull(store.getters.user));
    /* has token*/

    if(to.path == '/login'){ // 如果已经登录访问登录页，强制去首页
        next({
            path: '/app'
        });
    }

    if (validatenull(store.getters.user)) {
        store.dispatch('GetUserInfo').then(res => {
          //const roles = res.roles
          /*next({ ...to,
            replace: true
          })*/
          next();
        }).catch(() => {
          store.dispatch('FedLogOut').then(() => {
            next({
              path: '/login'
            })
            NProgress.done()
          })
        })
      } else {
        next()
      }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

// 寻找子菜单的父类
function findMenuParent(tag) {
  let tagCurrent = []
  const menu = store.getters.menu
  tagCurrent.push(tag)
  return tagCurrent
}

router.afterEach((to, from) => {
  NProgress.done()
/*  setTimeout(() => {
    const tag = store.getters.tag
    setTitle(tag.label)
    store.commit('SET_TAG_CURRENT', findMenuParent(tag))
  }, 0)*/
})
